// pages/brand_info/brand_info.js
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    brand_files: [],
    brand_other_files: [],
    brand_vc: [],
    brand_other_vc: [],
    cWidth: 0,
    cHeight: 0
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.onLoad()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 2000);
  },
  choose_brand_files: function (e) {
      var that = this;
      wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'], 
          success: function (photo) {
            var image_size = 5 * 1024 * 1024
            if (photo.tempFiles[0].size > image_size) {
              wx.showToast({
                title: '上传图片不能超过5M',
                icon: 'none',
                duration: 2000
              })
              return false
            }

            wx.getImageInfo({
              src: photo.tempFilePaths[0],
              success: function (res) {
                console.log(res);
                //---------利用canvas压缩图片--------------
                var ratio = 2;
                var canvasWidth = res.width //图片原始长宽
                var canvasHeight = res.height
                while (canvasWidth > 1024 || canvasHeight > 1024) {// 保证宽高在400以内
                  canvasWidth = Math.trunc(res.width / ratio)
                  canvasHeight = Math.trunc(res.height / ratio)
                  ratio++;
                }
                that.setData({
                  cWidth: canvasWidth,
                  cHeight: canvasHeight
                })

                //----------绘制图形并取出图片路径--------------
                var ctx = wx.createCanvasContext('seal_files')
                ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
                ctx.draw(false, setTimeout(function () {
                  wx.canvasToTempFilePath({
                    canvasId: 'seal_files',
                    destWidth: canvasWidth,
                    destHeight: canvasHeight,
                    success: function (result) {
                      console.log(result.tempFilePath)//最终图片路径

                      //上传图片
                      wx.showLoading({
                        title: '图片上传中',
                        icon: 'loading',
                        mask: true
                      })
                      wx.uploadFile({
                        url: util.reqUrl('V2/uploadBrand'),
                        header: util.headers(),
                        formData: { 'identity_token': util.getUserdata('identity_token') },
                        filePath: result.tempFilePath,
                        name: 'brand_' + that.data.brand_files.length,
                        success(res) {
                          wx.hideLoading()
                          console.log(res);
                          var rtn = JSON.parse(res.data)
                          if (rtn.code < 0) {
                            wx.showToast({
                              title: rtn.err,
                              icon: 'none',
                              duration: 2000
                            })
                            return false
                          }
                          console.log(rtn)
                          var brand_info = util.getUserdata('help_brand_info')
                          that.setData({
                            brand_vc: that.data.brand_vc.concat(rtn.verify_code)
                          });
                          brand_info.brand_vc = that.data.brand_vc
                          if (rtn.brand_register_code) {
                            brand_info.brand_register_code = rtn.brand_register_code
                            that.setData({
                              brand_register_code: rtn.brand_register_code
                            });
                          }
                          // if (rtn.possessor_name) {
                          //   brand_info.possessor_name = rtn.possessor_name
                          //   that.setData({
                          //     possessor_name: rtn.possessor_name
                          //   });
                          // }
                          // if (rtn.validity) {
                          //   let deadline = rtn.validity
                          //   let arr = deadline.split('-')
                          //   if (arr[0].length < 4){
                          //     brand_info.validity = '2020-01-01'
                          //   }else{
                          //     brand_info.validity = rtn.validity
                          //   }
                            
                          //   that.setData({
                          //     validity: brand_info.validity
                          //   });
                          // }
                          // if (rtn.address) {
                          //   brand_info.address = rtn.address
                          //   that.setData({
                          //     address: rtn.address
                          //   });
                          // }
                          // if (rtn.type_num) {
                          //   brand_info.type_num = rtn.type_num
                          //   that.setData({
                          //     type_num: rtn.type_num
                          //   });
                          // }
                          // if (rtn.project_option) {
                          //   brand_info.project_option = rtn.project_option
                          //   that.setData({
                          //     project_option: rtn.project_option
                          //   });
                          // }

                          that.setData({
                            type_num: '00',
                            validity: '2020-01-01',
                            possessor_name: '000000',
                            brand_name: '000000'
                          })

                          that.setData({
                            brand_files: that.data.brand_files.concat('https://gongzheng.ma.cn/MYPublic/' + rtn.image_name)
                          });
                          brand_info.brand_files = that.data.brand_files

                          util.setUserdata('help_brand_info', brand_info)
                        }
                      })

                    },
                    fail: function (res) {
                      console.log(res.errMsg)
                    }
                  })
                }, 500))
              }
            })
            // var brand_info = util.getUserdata('brand_info')
            // that.setData({
            //   brand_files: that.data.brand_files.concat('https://gongzheng.ma.cn/MYPublic/' + rtn.image_name)
            // });
            // brand_info.brand_files = that.data.brand_files
            // util.setUserdata('brand_info',brand_info)
          }
      })
  },
  choose_brand_other_files: function (e) {
      var that = this;
      wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'], 
          success: function (photo) {
            var image_size = 5 * 1024 * 1024
            if (photo.tempFiles[0].size > image_size) {
              wx.showToast({
                title: '上传图片不能超过5M',
                icon: 'none',
                duration: 2000
              })
              return false
            }

            wx.getImageInfo({
              src: photo.tempFilePaths[0], 
              success: function (res) {
                console.log(res);
                //---------利用canvas压缩图片--------------
                var ratio = 2;
                var canvasWidth = res.width //图片原始长宽
                var canvasHeight = res.height
                while (canvasWidth > 1024 || canvasHeight > 1024) {// 保证宽高在400以内
                  canvasWidth = Math.trunc(res.width / ratio)
                  canvasHeight = Math.trunc(res.height / ratio)
                  ratio++;
                }
                that.setData({
                  cWidth: canvasWidth,
                  cHeight: canvasHeight
                })

                //----------绘制图形并取出图片路径--------------
                var ctx = wx.createCanvasContext('brand_other_files')
                ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
                ctx.draw(false, setTimeout(function () {
                  wx.canvasToTempFilePath({
                    canvasId: 'brand_other_files',
                    destWidth: canvasWidth,
                    destHeight: canvasHeight,
                    success: function (result) {
                      console.log(result.tempFilePath)//最终图片路径
                      
                      //上传图片
                      wx.showLoading({
                        title: '图片上传中',
                        icon: 'loading',
                        mask: true
                      })
                      wx.uploadFile({
                        url: util.reqUrl('V2/uploadBrandOther'),
                        header: util.headers(),
                        formData: { 'identity_token': util.getUserdata('identity_token') },
                        filePath: result.tempFilePath,
                        name: 'brand_other_' + that.data.brand_other_files.length,
                        success(res) {
                          wx.hideLoading()
                          console.log(res);
                          var rtn = JSON.parse(res.data)
                          if (rtn.code < 0) {
                            wx.showToast({
                              title: rtn.err,
                              icon: 'none',
                              duration: 2000
                            })
                            return false
                          }
                          var brand_info = util.getUserdata('help_brand_info')
                          that.setData({
                            brand_other_vc: that.data.brand_other_vc.concat(rtn.verify_code)
                          });
                          brand_info.brand_other_vc = that.data.brand_other_vc

                          that.setData({
                            brand_other_files: that.data.brand_other_files.concat('https://gongzheng.ma.cn/MYPublic/' + rtn.image_name)
                          });
                          brand_info.brand_other_files = that.data.brand_other_files
                          util.setUserdata('help_brand_info', brand_info)
                        }
                      })
                      
                    },
                    fail: function (res) {
                      console.log(res.errMsg)
                    }
                  })
                },500))
              }
            })
            
          }
      })
  },
  preview_brand_files: function(e){
      wx.previewImage({
          current: e.currentTarget.id, 
          urls: this.data.brand_files 
      })
  },
  preview_brand_other_files: function(e){
      wx.previewImage({
          current: e.currentTarget.id, 
          urls: this.data.brand_other_files 
      })
  },
  touchStart: function(e){
    this.touchTimeStamp = e.timeStamp
  },
  touchEnd: function (e) {
    var diff = e.timeStamp - this.touchTimeStamp
    var tag = e.currentTarget.dataset.tag
    if (tag == 'brand_block'){
      diff >= 500 ? this.delete_brand_files(e) : this.preview_brand_files(e)
    } 
    if (tag == 'brand_other_block') {
      diff >= 500 ? this.delete_brand_other_files(e) : this.preview_brand_other_files(e)
    } 
  },
  delete_brand_files: function(e){
    var img_id = e.currentTarget.id;
    var that = this
    wx.showModal({
      title: '删除图片',
      content: '是否确认要删除该图片?',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          var brand_info = util.getUserdata('help_brand_info')
          console.log(img_id)
          console.log(brand_info.brand_files)
          var idx = util.array_search(brand_info.brand_files, img_id)
          console.log(idx)
          if (idx > -1) {
            brand_info.brand_files.splice(idx, 1)
            brand_info.brand_vc.splice(idx, 1)
          }
          util.setUserdata('help_brand_info', brand_info)
          that.reload()
        } else {
          console.log('用户点击辅助操作')
        }
      }
    });
    
  },
  delete_brand_other_files: function (e) {
    var img_id = e.currentTarget.id;
    var that = this
    wx.showModal({
      title: '删除图片',
      content: '是否确认要删除该图片?',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          var brand_info = util.getUserdata('help_brand_info')
          var idx = util.array_search(brand_info.brand_other_files, img_id)
          if (idx > -1) {
            brand_info.brand_other_files.splice(idx, 1)
            brand_info.brand_other_vc.splice(idx, 1)
          }
          util.setUserdata('help_brand_info', brand_info)
          that.reload()
        } else {
          console.log('用户点击辅助操作')
        }
      }
    });
  },
  brand_register_code_input: function(e){
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.brand_register_code = e.detail.value
    console.log(brand_info)
    this.setData({
      brand_register_code: brand_info.brand_register_code
    });
    util.setUserdata('help_brand_info',brand_info)
  },
  brand_name_input: function(e){
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.brand_name = e.detail.value
    console.log(brand_info)
    this.setData({
      brand_name: brand_info.brand_name
    });
    util.setUserdata('help_brand_info',brand_info)
  },
  possessor_name_input: function(e){
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.possessor_name = e.detail.value
    console.log(brand_info)
    this.setData({
      possessor_name: brand_info.possessor_name
    });
    util.setUserdata('help_brand_info',brand_info)
  },
  address_input: function(e){
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.address = e.detail.value
    console.log(brand_info)
    this.setData({
      address: brand_info.address
    });
    util.setUserdata('help_brand_info',brand_info);
  },
  type_num_input: function(e){
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.type_num = e.detail.value
    console.log(brand_info)
    this.setData({
      type_num: brand_info.type_num
    });
    util.setUserdata('help_brand_info',brand_info)
  },
  project_option_input: function(e){
    var brand_info = util.getUserdata('brand_info')
    brand_info.project_option = e.detail.value
    console.log(brand_info)
    this.setData({
      project_option: brand_info.project_option
    });
    util.setUserdata('brand_info',brand_info)
  },
  other_possessor_input: function(e){
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.other_possessor = e.detail.value
    console.log(brand_info)
    this.setData({
      other_possessor: brand_info.other_possessor
    });
    util.setUserdata('help_brand_info',brand_info)
  },
  validity_input: function(e){
    console.log(e)
    var brand_info = util.getUserdata('help_brand_info')
    brand_info.validity = e.detail.value
    console.log(brand_info)
    this.setData({
      validity: brand_info.validity
    });
    util.setUserdata('help_brand_info',brand_info)
  },
  save: function () {
    var brand_info = {}
    console.log(this.data)
    var that = this;
    var brand_files = this.data.brand_files;
    var brand_other_files = this.data.brand_other_files;
    var brand_register_code = this.data.brand_register_code;
    var brand_vc = this.data.brand_vc;
    var brand_other_vc = this.data.brand_other_vc;
    var brand_name = this.data.brand_name;
    var possessor_name = this.data.possessor_name;
    var address = this.data.address;
    var type_num = this.data.type_num;
    var other_possessor = this.data.other_possessor;
    var validity = this.data.validity;

    if(brand_files.length < 1) {
      wx.showToast({
        title: '请提交注册证照片',
        icon: 'none',
        duration: 2000
      })
      return false;
    }

    if (brand_register_code == '') {
      wx.showToast({
        title: '请输入商标注册号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }

    if (type_num == '') {
      type_num = '00'
    }

    if (brand_name == '') {
      brand_name = '000000'
    }

    if (possessor_name == '') {
      possessor_name = '000000'
    }

    // if (address == '') {
    //   wx.showToast({
    //     title: '请输入地址',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return false;
    // }

    if (validity == '') {
      validity = '2020-01-01'
    }

    
    brand_info.brand_files = brand_files
    brand_info.brand_other_files = brand_other_files
    brand_info.brand_register_code = brand_register_code
    brand_info.brand_vc = brand_vc
    brand_info.brand_other_vc = brand_other_vc
    brand_info.brand_name = brand_name
    brand_info.possessor_name = possessor_name
    brand_info.address = address
    brand_info.type_num = type_num
    brand_info.other_possessor = other_possessor
    brand_info.validity = validity
    console.log(brand_info);
    // return false;
    
    wx.showModal({
      title: '提示',
      content: '是否确认保存',
      success: function(sm) {
        if(sm.confirm) {
          console.log(brand_info);
          util.setUserdata('help_brand_info', brand_info)
          wx.reLaunch({
            url: '../help_get_notarization/help_get_notarization',
          })
          // wx.navigateBack({
          //   delta: 1
          // })
        }
      }
    })
    
  },
  clear_input: function(){
    var brand_info = {}
    this.setData({
      brand_files: brand_info.brand_files || [],
      brand_other_files: brand_info.brand_other_files || [],
      brand_vc: brand_info.brand_vc || [],
      brand_other_vc: brand_info.brand_other_vc || [],
      brand_register_code: brand_info.brand_register_code || '',
      brand_name: brand_info.brand_name || '',
      possessor_name: brand_info.possessor_name || '',
      address: brand_info.address || '',
      type_num: brand_info.type_num || '',
      project_option: brand_info.project_option || '',
      other_possessor: brand_info.other_possessor || '',
      validity: brand_info.validity || ''
    });
    console.log(brand_info)
    util.setUserdata('help_brand_info',brand_info)
  },
  reload: function(){
    var brand_info = util.getUserdata('help_brand_info')
    console.log(brand_info)
    this.setData({
      brand_files: brand_info.brand_files || [],
      brand_other_files: brand_info.brand_other_files || [],
      brand_vc: brand_info.brand_vc || [],
      brand_other_vc: brand_info.brand_other_vc || [],
      brand_register_code: brand_info.brand_register_code || '',
      brand_name: brand_info.brand_name || '',
      possessor_name: brand_info.possessor_name || '',
      address: brand_info.address || '',
      type_num: brand_info.type_num || '',
      project_option: brand_info.project_option || '',
      other_possessor: brand_info.other_possessor || '',
      validity: brand_info.validity || ''
    });
  },
  onLoad: function () {
    
    this.reload()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  touchTimeStamp: 0
})